package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.Category;
import com.example.demo.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;

    /**
     * 获取所有一级分类
     */
    @GetMapping("/level1")
    public AjaxResult getLevel1Categories() {
        try {
            List<Category> categories = categoryService.getCategoriesByLevel(1);
            return AjaxResult.success(categories);
        } catch (Exception e) {
            return AjaxResult.fail("获取一级分类失败: " + e.getMessage());
        }
    }

    /**
     * 根据父ID获取子分类
     */
    @GetMapping("/children/{parentId}")
    public AjaxResult getChildCategories(@PathVariable Integer parentId) {
        try {
            List<Category> children = categoryService.getChildCategories(parentId);
            return AjaxResult.success(children);
        } catch (Exception e) {
            return AjaxResult.fail("获取子分类失败: " + e.getMessage());
        }
    }

    /**
     * 获取完整的分类树（包含所有层级）
     */
    @GetMapping("/tree")
    public AjaxResult getCategoryTree() {
        try {
            List<Category> tree = categoryService.getCategoryTree();
            return AjaxResult.success(tree);
        } catch (Exception e) {
            return AjaxResult.fail("获取分类树失败: " + e.getMessage());
        }
    }

    /**
     * 根据关键词搜索分类
     */
    @GetMapping("/search")
    public AjaxResult searchCategories(
            @RequestParam String keyword,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false, defaultValue = "relevance") String sort) {
        try {
            if (keyword == null || keyword.trim().isEmpty()) {
                return AjaxResult.fail("搜索关键词不能为空");
            }
            
            Map<String, Object> searchResult = categoryService.searchCategoriesWithDetails(
                keyword, page, pageSize, sort);
            
            return AjaxResult.success(searchResult);
        } catch (Exception e) {
            return AjaxResult.fail("搜索分类失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类ID获取完整路径
     */
    // @GetMapping("/path/{categoryId}")
    // public AjaxResult getCategoryPath(@PathVariable Integer categoryId) {
    //     try {
    //         List<Category> path = categoryService.getCategoryPath(categoryId);
    //         return AjaxResult.success(path);
    //     } catch (Exception e) {
    //         return AjaxResult.fail("获取分类路径失败: " + e.getMessage());
    //     }
    // }

    /**
     * 获取指定层级的所有分类
     */
    @GetMapping("/level/{level}")
    public AjaxResult getCategoriesByLevel(@PathVariable Integer level) {
        try {
            List<Category> categories = categoryService.getCategoriesByLevel(level);
            return AjaxResult.success(categories);
        } catch (Exception e) {
            return AjaxResult.fail("获取分类列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取热门分类
     */
    @GetMapping("/hot")
    public AjaxResult getHotCategories() {
        try {
            List<Category> hotCategories = categoryService.getHotCategories();
            return AjaxResult.success(hotCategories);
        } catch (Exception e) {
            return AjaxResult.fail("获取热门分类失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类ID获取详细信息
     */
    @GetMapping("/{id}")
    public AjaxResult getCategoryById(@PathVariable Integer id) {
        try {
            Category category = categoryService.getCategoryById(id);
            return AjaxResult.success(category);
        } catch (Exception e) {
            return AjaxResult.fail("获取分类信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据分类路径获取分类信息
     */
    @GetMapping("/path")
    public AjaxResult getCategoryByPath(@RequestParam String path) {
        try {
            if (path == null || path.isEmpty()) {
                return AjaxResult.fail("分类路径不能为空");
            }
            
            // 分割路径字符串（例如：1.101.1001）
            String[] ids = path.split("\\.");
            List<Category> categories = new ArrayList<>();
            
            // 逐级获取分类信息
            for (String id : ids) {
                try {
                    Category category = categoryService.getCategoryById(Integer.parseInt(id));
                    if (category != null) {
                        categories.add(category);
                    }
                } catch (NumberFormatException e) {
                    return AjaxResult.fail("无效的分类ID");
                }
            }
            
            return AjaxResult.success(categories);
        } catch (Exception e) {
            return AjaxResult.fail("获取分类路径失败: " + e.getMessage());
        }
    }

    /**
     * 根据父分类路径获取子分类
     */
    @GetMapping("/children")
    public AjaxResult getChildrenByPath(@RequestParam String parentPath) {
        try {
            if (parentPath == null || parentPath.isEmpty()) {
                return AjaxResult.fail("父分类路径不能为空");
            }
            
            // 获取最后一级分类ID
            String[] ids = parentPath.split("\\.");
            String lastId = ids[ids.length - 1];
            
            try {
                Integer parentId = Integer.parseInt(lastId);
                List<Category> children = categoryService.getChildCategories(parentId);
                return AjaxResult.success(children);
            } catch (NumberFormatException e) {
                return AjaxResult.fail("无效的分类ID");
            }
        } catch (Exception e) {
            return AjaxResult.fail("获取子分类失败: " + e.getMessage());
        }
    }
}
